//
//  BLEStream.swift
//  WNLockDemo
//
//  Created by 裴威 on 30/08/2018.
//  Copyright © 2018 wunu. All rights reserved.
//

import Foundation


/// 输入流
class DataInputStream: NSObject {
    private var data: Data
    private var length: UInt = 0
    init(data: Data) {
        self.data = data
    }
    func readBytes(len: UInt) -> [UInt8] {
        if self.length >= self.data.count {
            return []
        }
        if len > self.data.count {
            return []
        }
        let bytes = [UInt8](self.data)
        let retBytes = bytes[Int(self.length)..<Int(self.length+len)]
        self.length += len
        return [UInt8](retBytes)
    }
}


/// 输出流
class DataOutputStream: NSObject {
    var data: Data = Data()
    private var length: UInt = 0
    //写入一个字节
    func write(uint8 v: UInt8) {
        data.append(v & 0xff)
        length += 1
    }
    //写入二个字节
    func write(uint16 v: UInt16) {
        var bytes = [UInt8]()
        bytes.append(UInt8(v >> 8) & 0xff)
        bytes.append(UInt8(v & 0xff))
        data.append(contentsOf: bytes)
        length += 2
    }
    // 写入四个字节
    func write(uint32 v: UInt32) {
        var bytes = [UInt8]()
        bytes.append(UInt8(v >> 24) & 0xff)
        bytes.append(UInt8(UInt32(v >> 16) & 0xff))
        bytes.append(UInt8(UInt32(v >> 8) & 0xff))
        bytes.append(UInt8(v & 0xff))
        data.append(contentsOf: bytes)
        length += 4
    }
    // 写入字节流
    func write(bytes v: Data) {
        data.append(v)
        length += UInt(v.count)
    }
}
